package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.Customer;
import com.zhentao.pojo.CustomerFollowup;
import com.zhentao.pojo.Member;
import com.zhentao.service.CustomerService;
import com.zhentao.service.CustomerFollowupService;
import com.zhentao.service.MemberService;
import com.zhentao.service.UserService;
import com.zhentao.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import com.zhentao.pojo.User;

/**
 * CRM管理控制器
 * @date: 2025/8/13 11:36
 * @author: ftt
 */
@RestController
@RequestMapping("/crm")
@CrossOrigin
public class CrmController {

    @Autowired
    private CustomerService customerService;
    
    @Autowired
    private MemberService memberService;
    
    @Autowired
    private CustomerFollowupService customerFollowupService;
    
    @Autowired
    private UserService userService;

    // 统计结果内部类
    public static class CustomerStats {
        public final long totalCount;
        public final long activeCount;
        public final long inactiveCount;
        
        public CustomerStats(long totalCount, long activeCount, long inactiveCount) {
            this.totalCount = totalCount;
            this.activeCount = activeCount;
            this.inactiveCount = inactiveCount;
        }
    }
    
    public static class MemberStats {
        public final long totalCount;
        public final long activeCount;
        public final long inactiveCount;
        
        public MemberStats(long totalCount, long activeCount, long inactiveCount) {
            this.totalCount = totalCount;
            this.activeCount = activeCount;
            this.inactiveCount = inactiveCount;
        }
    }
    
    public static class FollowupStats {
        public final long totalCount;
        public final long inProgressCount;
        public final long completedCount;
        
        public FollowupStats(long totalCount, long inProgressCount, long completedCount) {
            this.totalCount = totalCount;
            this.inProgressCount = inProgressCount;
            this.completedCount = completedCount;
        }
    }
    
    public static class ReconciliationInfo {
        public final String message;
        public final String note;
        
        public ReconciliationInfo(String message, String note) {
            this.message = message;
            this.note = note;
        }
    }

    // ==================== 客户信息管理 ====================
    
    /**
     * 分页查询客户信息
     */
    @GetMapping("/customer/list")
    public Result<IPage<Customer>> getCustomerList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String contact,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) Integer status) {
        
        try {
            Page<Customer> page = new Page<>(current, size);
            QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
            
            if (name != null && !name.trim().isEmpty()) {
                queryWrapper.like("name", name.trim());
            }
            if (contact != null && !contact.trim().isEmpty()) {
                queryWrapper.like("contact", contact.trim());
            }
            if (phone != null && !phone.trim().isEmpty()) {
                queryWrapper.like("phone", phone.trim());
            }
            if (status != null) {
                queryWrapper.eq("status", status);
            }
            
            queryWrapper.orderByDesc("id");
            
            IPage<Customer> result = customerService.page(page, queryWrapper);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询客户信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询客户信息
     */
    @GetMapping("/customer/{id}")
    public Result<Customer> getCustomerById(@PathVariable Long id) {
        try {
            Customer customer = customerService.getById(id);
            if (customer != null) {
                return Result.success(customer);
            } else {
                return Result.error("客户信息不存在");
            }
        } catch (Exception e) {
            return Result.error("查询客户信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 新增客户信息
     */
    @PostMapping("/customer")
    public Result<String> addCustomer(@RequestBody Customer customer) {
        try {
            customer.setCreateTime(new Date());
            boolean success = customerService.save(customer);
            if (success) {
                return Result.success("新增客户成功");
            } else {
                return Result.error("新增客户失败");
            }
        } catch (Exception e) {
            return Result.error("新增客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新客户信息
     */
    @PutMapping("/customer")
    public Result<String> updateCustomer(@RequestBody Customer customer) {
        try {
            boolean success = customerService.updateById(customer);
            if (success) {
                return Result.success("更新客户成功");
            } else {
                return Result.error("更新客户失败");
            }
        } catch (Exception e) {
            return Result.error("更新客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除客户信息
     */
    @DeleteMapping("/customer/{id}")
    public Result<String> deleteCustomer(@PathVariable Long id) {
        try {
            boolean success = customerService.removeById(id);
            if (success) {
                return Result.success("删除客户成功");
            } else {
                return Result.error("删除客户失败");
            }
        } catch (Exception e) {
            return Result.error("删除客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除客户信息
     */
    @DeleteMapping("/customer/batch")
    public Result<String> batchDeleteCustomer(@RequestBody List<Long> ids) {
        try {
            boolean success = customerService.removeByIds(ids);
            if (success) {
                return Result.success("批量删除客户成功");
            } else {
                return Result.error("批量删除客户失败");
            }
        } catch (Exception e) {
            return Result.error("批量删除客户失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取客户统计信息
     */
    @GetMapping("/customer/stats")
    public Result<CustomerStats> getCustomerStats() {
        try {
            long totalCount = customerService.count();
            long activeCount = customerService.count(new QueryWrapper<Customer>().eq("status", 1));
            long inactiveCount = customerService.count(new QueryWrapper<Customer>().eq("status", 0));
            
            CustomerStats stats = new CustomerStats(totalCount, activeCount, inactiveCount);
            return Result.success("获取统计信息成功", stats);
        } catch (Exception e) {
            return Result.error("获取客户统计信息失败：" + e.getMessage());
        }
    }

    // ==================== 会员信息管理 ====================
    
    /**
     * 分页查询会员信息
     */
    @GetMapping("/member/list")
    public Result<IPage<Member>> getMemberList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) Integer status) {
        
        try {
            Page<Member> page = new Page<>(current, size);
            QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
            
            if (name != null && !name.trim().isEmpty()) {
                queryWrapper.like("name", name.trim());
            }
            if (phone != null && !phone.trim().isEmpty()) {
                queryWrapper.like("phone", phone.trim());
            }
            if (status != null) {
                queryWrapper.eq("status", status);
            }
            
            queryWrapper.orderByDesc("id");
            
            IPage<Member> result = memberService.page(page, queryWrapper);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询会员信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询会员信息
     */
    @GetMapping("/member/{id}")
    public Result<Member> getMemberById(@PathVariable Long id) {
        try {
            Member member = memberService.getById(id);
            if (member != null) {
                return Result.success(member);
            } else {
                return Result.error("会员信息不存在");
            }
        } catch (Exception e) {
            return Result.error("查询会员信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 新增会员信息
     */
    @PostMapping("/member")
    public Result<String> addMember(@RequestBody Member member) {
        try {
            member.setCreateTime(new Date());
            boolean success = memberService.save(member);
            if (success) {
                return Result.success("新增会员成功");
            } else {
                return Result.error("新增会员失败");
            }
        } catch (Exception e) {
            return Result.error("新增会员失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新会员信息
     */
    @PutMapping("/member")
    public Result<String> updateMember(@RequestBody Member member) {
        try {
            boolean success = memberService.updateById(member);
            if (success) {
                return Result.success("更新会员成功");
            } else {
                return Result.error("更新会员失败");
            }
        } catch (Exception e) {
            return Result.error("更新会员失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除会员信息
     */
    @DeleteMapping("/member/{id}")
    public Result<String> deleteMember(@PathVariable Long id) {
        try {
            boolean success = memberService.removeById(id);
            if (success) {
                return Result.success("删除会员成功");
            } else {
                return Result.error("删除会员失败");
            }
        } catch (Exception e) {
            return Result.error("删除会员失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除会员信息
     */
    @DeleteMapping("/member/batch")
    public Result<String> batchDeleteMember(@RequestBody List<Long> ids) {
        try {
            boolean success = memberService.removeByIds(ids);
            if (success) {
                return Result.success("批量删除会员成功");
            } else {
                return Result.error("批量删除会员失败");
            }
        } catch (Exception e) {
            return Result.error("批量删除会员失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取会员统计信息
     */
    @GetMapping("/member/stats")
    public Result<MemberStats> getMemberStats() {
        try {
            long totalCount = memberService.count();
            long activeCount = memberService.count(new QueryWrapper<Member>().eq("status", 1));
            long inactiveCount = memberService.count(new QueryWrapper<Member>().eq("status", 0));
            
            MemberStats stats = new MemberStats(totalCount, activeCount, inactiveCount);
            return Result.success("获取统计信息成功", stats);
        } catch (Exception e) {
            return Result.error("获取会员统计信息失败：" + e.getMessage());
        }
    }

    // ==================== 客户跟进管理 ====================
    
    /**
     * 分页查询客户跟进信息
     */
    @GetMapping("/followup/list")
    public Result<IPage<CustomerFollowup>> getFollowupList(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long userId) {
        
        try {
            Page<CustomerFollowup> page = new Page<>(current, size);
            QueryWrapper<CustomerFollowup> queryWrapper = new QueryWrapper<>();
            
            if (customerId != null) {
                queryWrapper.eq("customer_id", customerId);
            }
            if (status != null) {
                queryWrapper.eq("status", status);
            }
            if (userId != null) {
                queryWrapper.eq("user_id", userId);
            }
            
            queryWrapper.orderByDesc("followup_time");
            
            IPage<CustomerFollowup> result = customerFollowupService.page(page, queryWrapper);
            
            // 关联查询客户名称
            if (result.getRecords() != null && !result.getRecords().isEmpty()) {
                for (CustomerFollowup followup : result.getRecords()) {
                    if (followup.getCustomerId() != null) {
                        Customer customer = customerService.getById(followup.getCustomerId());
                        if (customer != null) {
                            followup.setCustomerName(customer.getName());
                        }
                    }
                    // 关联查询跟进人名称
                    if (followup.getUserId() != null) {
                        User user = userService.getById(followup.getUserId());
                        if (user != null) {
                            followup.setUserName(user.getRealName());
                        }
                    }
                }
            }
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询客户跟进信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据ID查询客户跟进信息
     */
    @GetMapping("/followup/{id}")
    public Result<CustomerFollowup> getFollowupById(@PathVariable Long id) {
        try {
            CustomerFollowup followup = customerFollowupService.getById(id);
            if (followup != null) {
                // 关联查询客户名称
                if (followup.getCustomerId() != null) {
                    Customer customer = customerService.getById(followup.getCustomerId());
                    if (customer != null) {
                        followup.setCustomerName(customer.getName());
                    }
                }
                // 关联查询跟进人名称
                if (followup.getUserId() != null) {
                    User user = userService.getById(followup.getUserId());
                    if (user != null) {
                        followup.setUserName(user.getRealName());
                    }
                }
                return Result.success(followup);
            } else {
                return Result.error("客户跟进信息不存在");
            }
        } catch (Exception e) {
            return Result.error("查询客户跟进信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 新增客户跟进信息
     */
    @PostMapping("/followup")
    public Result<String> addFollowup(@RequestBody CustomerFollowup followup) {
        try {
            followup.setCreateTime(new Date());
            if (followup.getFollowupTime() == null) {
                followup.setFollowupTime(new Date());
            }
            boolean success = customerFollowupService.save(followup);
            if (success) {
                return Result.success("新增客户跟进成功");
            } else {
                return Result.error("新增客户跟进失败");
            }
        } catch (Exception e) {
            return Result.error("新增客户跟进失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新客户跟进信息
     */
    @PutMapping("/followup")
    public Result<String> updateFollowup(@RequestBody CustomerFollowup followup) {
        try {
            boolean success = customerFollowupService.updateById(followup);
            if (success) {
                return Result.success("更新客户跟进成功");
            } else {
                return Result.error("更新客户跟进失败");
            }
        } catch (Exception e) {
            return Result.error("更新客户跟进失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除客户跟进信息
     */
    @DeleteMapping("/followup/{id}")
    public Result<String> deleteFollowup(@PathVariable Long id) {
        try {
            boolean success = customerFollowupService.removeById(id);
            if (success) {
                return Result.success("删除客户跟进成功");
            } else {
                return Result.error("删除客户跟进失败");
            }
        } catch (Exception e) {
            return Result.error("删除客户跟进失败：" + e.getMessage());
        }
    }
    
    /**
     * 批量删除客户跟进信息
     */
    @DeleteMapping("/followup/batch")
    public Result<String> batchDeleteFollowup(@RequestBody List<Long> ids) {
        try {
            boolean success = customerFollowupService.removeByIds(ids);
            if (success) {
                return Result.success("批量删除客户跟进成功");
            } else {
                return Result.error("批量删除客户跟进失败");
            }
        } catch (Exception e) {
            return Result.error("批量删除客户跟进失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取客户跟进统计信息
     */
    @GetMapping("/followup/stats")
    public Result<FollowupStats> getFollowupStats() {
        try {
            long totalCount = customerFollowupService.count();
            long inProgressCount = customerFollowupService.count(new QueryWrapper<CustomerFollowup>().eq("status", 1));
            long completedCount = customerFollowupService.count(new QueryWrapper<CustomerFollowup>().eq("status", 2));
            
            FollowupStats stats = new FollowupStats(totalCount, inProgressCount, completedCount);
            return Result.success("获取统计信息成功", stats);
        } catch (Exception e) {
            return Result.error("获取客户跟进统计信息失败：" + e.getMessage());
        }
    }

    // ==================== 客户对账管理 ====================
    
    /**
     * 获取客户对账信息
     */
    @GetMapping("/reconciliation")
    public Result<ReconciliationInfo> getCustomerReconciliation(
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        try {
            // 这里可以根据实际业务需求实现客户对账逻辑
            // 目前返回示例数据
            ReconciliationInfo info = new ReconciliationInfo("客户对账功能待完善", "需要根据实际业务需求实现具体的对账逻辑");
            return Result.success("获取客户对账信息成功", info);
        } catch (Exception e) {
            return Result.error("获取客户对账信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 导出客户对账报表
     */
    @GetMapping("/reconciliation/export")
    public Result<String> exportCustomerReconciliation(
            @RequestParam(required = false) Long customerId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        try {
            // 这里可以实现导出逻辑
            return Result.success("导出功能待完善，请稍后使用");
        } catch (Exception e) {
            return Result.error("导出客户对账报表失败：" + e.getMessage());
        }
    }
}
